package hust.cs.javacourse.search.run;

import hust.cs.javacourse.search.index.impl.Term;
import hust.cs.javacourse.search.query.AbstractHit;
import hust.cs.javacourse.search.query.AbstractIndexSearcher;
import hust.cs.javacourse.search.query.Sort;
import hust.cs.javacourse.search.query.impl.IndexSearcher;
import hust.cs.javacourse.search.query.impl.SimpleSorter;
import hust.cs.javacourse.search.util.Config;
import hust.cs.javacourse.search.util.StringSplitter;

import java.util.Scanner;
import java.util.List;

/**
 * 测试搜索
 */
public class TestSearchIndex {
    /**
     *  搜索程序入口
     * @param args ：命令行参数
     */Q
    public static void main(String[] args){
        Sort simpleSorter = new SimpleSorter();
        String indexFile = Config.INDEX_DIR + "index.dat";
        AbstractIndexSearcher searcher = new IndexSearcher();
        searcher.open(indexFile);
        Scanner input=new Scanner(System.in);
        StringSplitter splitter=new StringSplitter();
        splitter.setSplitRegex(Config.STRING_SPLITTER_REGEX);
        System.out.println("请输入搜索词，注意逻辑词是全大写，比如说OR和AND。输入Q退出程序。");
        String word=input.nextLine();
        while(!word.equals("Q")) {//输入”Q“退出程序
            List<String> term= splitter.splitByRegex(word);
            AbstractHit[] hits = null;
            if(term.size()==1) {//实现单个搜索
                hits = searcher.search(new Term(word), simpleSorter);
            }
            else if(term.size()==3 && term.get(1).equals("OR")){//实现或OR逻辑搜索
                hits = searcher.search(new Term(term.get(0)), new Term(term.get(2)), simpleSorter, AbstractIndexSearcher.LogicalCombination.OR);
            }
            else if(term.size()==3 && term.get(1).equals("AND")){//实现与AND逻辑搜索
                hits = searcher.search(new Term(term.get(0)), new Term(term.get(2)), simpleSorter, AbstractIndexSearcher.LogicalCombination.AND);
            }
            else{//输入不合法，要求重新输入
                System.out.println("输入不合法！仔细一点！我是不会迁就你的！");
            }
            if (hits!=null) {
                for (AbstractHit hit : hits) {
                    System.out.println(hit);
                }
            }
            else{
                System.out.println("很遗憾！没有满足要求的结果！");
            }
            System.out.println("请继续输入搜索词，注意逻辑词是全大写，比如说OR和AND。或者输入Q退出程序。");
            word=input.nextLine();//继续等待外部设备输入
        }
        System.out.println("欢迎使用本系统！下次再见！");
    }
}
